package com.watchmen.selenium;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v101.network.Network;
import org.openqa.selenium.remote.Augmenter;

/**
 * @author kk
 * @Description Selenium DevTools功能演示
 */
public class SeleniumDevTools {

	public static void main(String[] args) throws InterruptedException {
		String webDriverDir = "浏览器驱动路径";
		// 加载驱动
		System.setProperty("webdriver.chrome.driver", webDriverDir);
		// 创建驱动对象
		WebDriver driver = new ChromeDriver();

		driver = new Augmenter().augment(driver);
		DevTools devTools = ((HasDevTools) driver).getDevTools();
		devTools.createSession();
		devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
		// 获取Request信息
		devTools.addListener(Network.requestWillBeSent(), res -> {
			System.out.println("RequestHeaders:" + res.getRequest().getHeaders());
			System.out.println("RequestHeaders:" + res.getRequest().getUrl());
		});

		// 获取Response信息
		devTools.addListener(Network.responseReceived(), res -> {
			System.out.println("ResponseHeaders:" + res.getResponse().getHeaders());
			System.out.println("ResponseURL:" + res.getResponse().getUrl());
		});
		driver.get("https://www.baidu.com/");

		TimeUnit.MILLISECONDS.sleep(4500);
	}
}
